import 'package:film/service/api_service.dart';
import 'package:get/get.dart';

/// 忘记密码页面控制器
class ForgotPasswordController extends GetxController {
  final DioService apiService = DioService();

  /// 账号（邮箱）
  var account = ''.obs;

  /// 验证码
  var code = ''.obs;

  /// 新密码
  var newPassword = ''.obs;

  /// 是否正在发送验证码
  var sending = false.obs;

  /// 倒计时秒数
  var seconds = 0.obs;

  /// 发送验证码
  void sendCode() async {
    if (account.value.isEmpty) {
      Get.snackbar('提示', '请填写邮箱');
      return;
    }
    sending.value = true;
    seconds.value = 60;
    final ApiResponse<void> response = await apiService.sendEmail(email: account.value);
    if (response.success) {
      Get.snackbar(
        '成功',
        '发送成功！',
        duration: Duration(seconds: 1),
      );
    } else {
      Get.snackbar(
        '错误',
        '发送失败: ${response.message}',
        duration: Duration(seconds: 1),
      );
    }
    // 启动倒计时
    while (seconds.value > 0) {
      await Future.delayed(const Duration(seconds: 1));
      seconds.value--;
    }
    sending.value = false;
  }

  /// 提交找回密码
  void submit() async {
    if (account.value.isEmpty || code.value.isEmpty || newPassword.value.isEmpty) {
      Get.snackbar('提示', '请填写所有字段');
      return;
    }
    final ApiResponse<void> response = await apiService.forgotPassword(
      email: account.value,
      verifyCode: code.value,
      newPassword: newPassword.value,
    );
    if (response.success) {
      Get.snackbar(
        '成功',
        '修改成功！',
        duration: Duration(seconds: 1),
      );
    }
    // 清空输入
    account.value = '';
    code.value = '';
    newPassword.value = '';
  }
}
